package com.easyfun.healthmagicbox;

import java.sql.SQLException;
import java.util.List;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.easyfun.healthmagicbox.base.BaseActivity;
import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.bluetooth.BTMessageHandler;
import com.easyfun.healthmagicbox.bluetooth.BluetoothChatService;
import com.easyfun.healthmagicbox.bluetooth.meng.MengHandler;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.pojo.PersonProfile;
import com.easyfun.healthmagicbox.util.URIConverter;
import com.easyfun.healthmagicbox.widget.SelectInputCatalogPopupWindow;
import com.j256.ormlite.dao.Dao;

public class FastUIActivity extends BaseActivity implements DatabaseAccess{
	private final String LOG_TAG = getClass().getSimpleName();

	private ImageView m_imageHead;
	private String imagefilename;
	// EditText txtShareCode ;
	TextView txtSharelist;
	TextView seperator2;
	//
	SelectInputCatalogPopupWindow menuWindow;

	ListView listLastActs;

	private Button m_hardware;

	private Button m_picture;

	private BluetoothAdapter mBluetoothAdapter = null;

	private BluetoothChatService mChatService;

	protected Object mConnectedDeviceName;

	// Debugging
	private static final String TAG = FastUIActivity.class.getSimpleName();
	private static final boolean D = true;


	
	private static final int REQUEST_ENABLE_BT = 2;
	 
	// Key names received from the BluetoothChatService Handler
	public static final String DEVICE_NAME = "device_name";
	public static final String TOAST = "toast";

	

	private BTMessageHandler mHandler ;

	

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (D)
			Log.d(TAG, "onActivityResult " + resultCode);
		switch (requestCode) {
		case REQUEST_ENABLE_BT:
			// When the request to enable Bluetooth returns
			if (resultCode == Activity.RESULT_OK) {
				// Bluetooth is now enabled, so set up a chat session
				setupChat();
			} else {
				// User did not enable Bluetooth or an error occured
				Log.d(TAG, "BT not enabled");
				Toast.makeText(this, R.string.bt_not_enabled_leaving,
						Toast.LENGTH_SHORT).show();
				finish();
			}
		}
	}
	private void setupChat() {
        Log.d(TAG, "setupChat()");
        mChatService = new BluetoothChatService(this, mHandler,"FastUIActivity");

    }
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.fastui);
		if (!checkPersonId())
			return;
		//addbackButton should after setting content view
		addbackButton(this);
		mHandler = new MengHandler(m_personid,FastUIActivity.this,null);
		m_imageHead = (ImageView) findViewById(R.id.fastuiimagehead);

		try {
			Dao<PersonProfile, Integer> dao = getHelper(this)
					.getPersonProfileDao();
			List<PersonProfile> pps;
			pps = dao.queryBuilder().where().eq("personID", m_personid).query();
			if (pps.size() >= 1) {
				imagefilename = pps.get(0).getImageFileName();
				Bitmap img = URIConverter.getHeadFromAppSDCard(this,
						imagefilename, pps.get(0).getPersonID(),pps.get(0).getSex());
				m_imageHead.setImageBitmap(img);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// Get local Bluetooth adapter
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		//mChatService = new BluetoothChatService(this, mHandler ,"FastUIActivity");
		setupChat();
		m_hardware = (Button) findViewById(R.id.butFastUIHardware);
		
		m_hardware.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String address = "7F:69:7A:5A:80:EE";//7F:69:7A:5A:80:EE
				// Get the BLuetoothDevice object
				BluetoothDevice device = mBluetoothAdapter
						.getRemoteDevice(address);
				// Attempt to connect to the device
				mChatService.connect(device);

			}
		});
		m_picture = (Button) findViewById(R.id.butFastUIPicture);

	}
	@Override
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        // Otherwise, setup the chat session
        } else {
            if (mChatService == null)  
            	setupChat();
        }
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if(D) Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
              // Start the Bluetooth chat services
              mChatService.start();
            }
        }
    }
	
	

	

	@Override
	public DatabaseHelper getHelper(Context context) {

		return DatabaseAccessImplementation.getInstance().getHelper(context);
	}


}
